﻿using System.IO;
using K9Nano.Updater.Utils;

namespace K9Nano.Updater.Pipes;

public class DownloadPipe : UpdatePipeBase
{
    public DownloadPipe()
    {
        PipeName = "下载";
    }

    protected override bool CanInvoke(UpdateContext context)
    {
        if (context.TargetVersion is null)
        {
            context.LogWarning("目标版本为空，无法执行下载任务");
            context.Terminated = true;
            return false;
        }
        return base.CanInvoke(context);
    }

    protected override async Task InvokeCoreAsync(UpdateContext context, CancellationToken cancellation)
    {
        var client = context.GetService<IUpdateClient>();
        context.LogInformation("开始下载更新文件，目标版本为{version}", context.TargetVersion);
        var downloadRoot = context.GetDownloadDirectory();
        if (Directory.Exists(downloadRoot))
        {
            PathUtils.ForceDeleteDirectory(downloadRoot);
        }
        Directory.CreateDirectory(downloadRoot);

        var package = await client.GetReleaseMetadataAsync(context.TargetVersion!, cancellation);
        if(package == null)
        {
            context.LogError("没有获取到有效的更新数据");
            return;
        }
        context.Package = package;
        var packageFile = Path.Combine(downloadRoot, Constants.PackageFileName);
        await JsonUtils.SaveAsync(package, packageFile);

        foreach (var item in package.Files)
        {
            context.LogInformation("开始下载更新文件: {file}", item.FileUri);
            var savePath = item.GetSavePath(downloadRoot);
            await client.DownloadAsync(context.TargetVersion!, item.FileUri, savePath, context.ReportProgress, cancellation);
            context.LogInformation("完成下载更新文件: {file}", item.FileUri);

        }
        context.LogInformation("下载更新文件完成，目标版本为{version}", context.TargetVersion);
    }
}
